package com.beta.cat.utils;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;

/**
 * 对称加解密算法工具
 *
 * @Description
 * @Author
 **/
@Slf4j
public class AESUtil {
    private static final String AES = "AES";
    //待家军提供正式密钥
    private static final String AES_KEY = "66666666";

    private static final String ALGORITHMSTR = "AES/CBC/PKCS7Padding";

    private static final String MODE = "BC";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @return
     */
    public static byte[] encrypt(String content) {
        try {
            SecretKeySpec key = new SecretKeySpec(AES_KEY.getBytes(StandardCharsets.UTF_8), AES);
            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(new byte[16]);
            cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);

            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            return cipher.doFinal(byteContent);
        } catch (Exception e) {
            log.error("when encrypt content error, content:{}, error:{}", content, e);
        }
        return null;
    }

    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @return
     */
    public static String encrypt(String content, String aesKey) {
        try {
            SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8), AES);
            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(new byte[16]);
            cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);

            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            byte[] contents = cipher.doFinal(byteContent);

            return parseByte2HexStr(contents);
        } catch (Exception e) {
            log.error("when encrypt content error, content:{}, error:{}", content, e);
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content 待解密内容
     * @return
     */
    public static byte[] decrypt(byte[] content, String aesKey) {
        try {
            SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8), AES);
            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(new byte[16]);
            cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
            return cipher.doFinal(content);
        } catch (Exception e) {
            log.error("when decrypt content error, error:{}", e);
        }
        return null;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static String decrypt(String content) {
        byte[] decryptFrom = parseHexStr2Byte(content);
        byte[] decryptResult = decrypt(decryptFrom, AES_KEY);
        if (decryptResult == null) {
            return "";
        }
        return new String(decryptResult, StandardCharsets.UTF_8);
    }

    public static String decrypt(String content, String aesKey) {
        byte[] decryptFrom = parseHexStr2Byte(content);
        byte[] decryptResult = decrypt(decryptFrom, aesKey);
        if (decryptResult == null) {
            return "";
        }
        return new String(decryptResult, StandardCharsets.UTF_8);
    }


}
